#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <unistd.h>

using namespace std;

int main() {
    int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in serv_addr{};
    memset(&serv_addr, 0, sizeof serv_addr);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    serv_addr.sin_port = htons(9520);

    bind(serv_sock, (sockaddr *) &serv_addr, sizeof serv_addr);
    listen(serv_sock, 20);

    struct sockaddr_in sock_addr{};
    socklen_t sock_addr_size = sizeof(sock_addr);
    cout << "服务端启动成功。。。" << endl;

    while (1) {
        int clint_sock = accept(serv_sock, (struct sockaddr *) &sock_addr, &sock_addr_size);
        cout << "连接客户端" << inet_ntoa(sock_addr.sin_addr) << ":" << ntohs(sock_addr.sin_port) << endl;

        char str[2];
        int8_t flag = 0;
        ssize_t strlens;
        // 读取客户端的数据
        while ((strlens = read(clint_sock, str, sizeof str)) > 0) {
            if(str[0]=='q'){
                flag = 1;
            }
            string s(str,0,strlens);
            cout << "读取" << strlens << "字节==>" << s << endl;
            send(clint_sock, str, strlens * sizeof(char),0);
        }
        shutdown(clint_sock, SHUT_WR);
        if(flag){
            cout<<"服务端退出成功..."<<endl;
            break;
        }
    }
    close(serv_sock);
    return 0;
}